﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace BuildingBlocks.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddCustomSwagger(this IServiceCollection services,IConfiguration configuration)
    {
        var origin = configuration.GetSection("Swagger:GatewayURL").Get<string>() ?? "";
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "My Microservice API",
                Version = "v1",
                Description = "统一配置的 Swagger 文档"
            });
            
            // 通过网关访问时的 URL
            c.AddServer(new OpenApiServer
            {
                Url = origin,
                Description = "Gateway URL"
            });

            // 如果需要加认证支持，可在这里添加：
            // c.AddSecurityDefinition(...);
            // c.AddSecurityRequirement(...);
            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Name = "Authorization",
                Type = SecuritySchemeType.Http,   // 改成 Http
                Scheme = "Bearer",                // 这里指定 Bearer
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Description = "请输入 JWT Token，无需输入 Bearer 前缀"
            });

            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
               {
                  new OpenApiSecurityScheme
                   {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                  },
                  new string[]{}
                }
            });
        });

        return services;
    }

    public static IServiceCollection AddCustomCors(this IServiceCollection services, IConfiguration configuration)
    {
        var origins = configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
        services.AddCors(options =>
        {
            options.AddPolicy("DefaultCorsPolicy", policy =>
            {
                policy.WithOrigins(origins)
                      .AllowAnyHeader()
                      .AllowAnyMethod();
            });
        });
        return services;
    }
}
